<!--
 * @Author: cjy
 * @Date: 2020-09-16 14:51:11
 * @LastEditors: Please set LastEditors
 * @Descripttion: 
 * @LastEditTime: 2022-02-15 18:44:25
 * @FilePath: \vue-openlayers\src\views\vectorJSON\VectorJSON.vue
-->
<template>
  <div class="vm">
    <h2 class="h-title">矢量图 JSON</h2>
    <div id="map" class="map-x"></div>

    <div class="explain"></div>
  </div>
</template>

<script>
import "ol/ol.css";
import ZJS from "@/assets/data/xingzhengquhua/zj.json";
import { Map, View } from "ol";
import SourceVector from "ol/source/Vector";
import LayerVector from "ol/layer/Vector";
import GeoJSON from "ol/format/GeoJSON";
import Tile from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import OSM from "ol/source/OSM";
import { fromLonLat } from "ol/proj";

export default {
  name: "VectorJSON",
  data() {
    return {
      map: null,
      source: new SourceVector({
        features: new GeoJSON().readFeatures(ZJS, {
          dataProjection: "EPSG:4326",
          featureProjection: "EPSG:3857",
        }),
      }),
      // source01: new SourceVector({
      //   features: new GeoJSON().readFeatures(WNZHOU, {
      //     // dataProjection: 'EPSG:4326',
      //     featureProjection: "EPSG:3857",
      //   }),
      // }),
      view: new View({
        // projection: "EPSG:4326",
        // center: [116.403963,39.915119], // 中国
        center: fromLonLat([116.403963, 39.915119]), // 中国
        zoom: 3,
      }),
    };
  },
  methods: {
    initMap() {
      let base = new Tile({
        // source: new OSM(), // OSM图层数据源
        source: new XYZ({
          url: "http://t0.tianditu.com/DataServer?T=vec_c&x={x}&y={y}&l={z}&tk=4d314458b2e0a90a498c0ae62142c9fd",
          projection: "EPSG:4326",
        }),
      });

      this.map = new Map({
        target: "map",
        layers: [
          new LayerVector({
            source: this.source,
          }),
          // new LayerVector({
          //   source: this.source01,
          // }),
        ],
        view: this.view,
      });

      //点击事件
      this.map.on("click", (evt) => {
        // let pix = this.map.getE
        let features = this.map.forEachFeatureAtPixel(
          evt.pixel,
          function (feature) {
            return feature;
          }
        );

        if (!features) {
          console.log("没有选择到数据……");
          return;
        }

        console.log(
          features.getGeometry().getType(),
          "======getType==========="
        );
        if (features.getGeometry().getType() == "MultiPolygon") {
          console.log(
            "您点击的图形类型是: " + features.getGeometry().getType()
          );
        } else {
          console.log("没有选择到数据……");
        }
      });
    },
  },
  mounted() {
    this.initMap();
    // console.log(this.source01.getFeatures());
  },
};
</script>

<style>
</style>